package com.cool4j.generator.builder

import com.cool4j.generator.config.GeneratorConstants
import com.cool4j.generator.entity.Column
import com.cool4j.generator.entity.Table
import com.cool4j.generator.exception.ExceptionMessage
import com.cool4j.generator.util.GeneratorUtil
import com.cool4j.generator.util.LogUtil
import com.cool4j.view.entity.HandlerVO
import freemarker.template.Configuration
import freemarker.template.TemplateException
import org.apache.commons.lang3.StringUtils

/**
 * 实体类构造器类
 *
 * @author Frank create on 16/1/8 14:04
 */
class EntityBuilder extends BaseBuilder {

    @Override
    boolean builder(Table table, String packagePath, HandlerVO handlerVO, Configuration config) {
        try {
            createEntity(table, packagePath, config, handlerVO)
            createParam(table, packagePath, config, handlerVO)
        } catch (IOException e) {
            LogUtil.logging(ExceptionMessage.LOG_ENTITY_BUILDER_IO_EXCEPTION, e)
            return false
        } catch (TemplateException e) {
            LogUtil.logging(ExceptionMessage.LOG_ENTITY_BUILDER_TEMPLATE_EXCEPTION, e)
            return false
        } catch (Exception e) {
            LogUtil.logging(ExceptionMessage.LOG_ENTITY_BUILDER_OTHER_EXCEPTION, e)
            return false
        }
        return true
    }

    /**
     * 实体类创建方法
     *
     * @param table - 数据库表对象
     * @param packagePath - 包路径
     * @param config - 模板配置对象
     * @param handlerVO - 代码生成器界面设置内容
     * @throws IOException - IO 异常
     * @throws TemplateException - 模板异常
     */
    private void createEntity(Table table, String packagePath, Configuration config,
                              HandlerVO handlerVO) throws IOException, TemplateException {
        /* 获取或创建一个模板 */
        def template = config.getTemplate("Entity.ftl", "UTF-8")
        def dataMap = getDataMap(table, packagePath, handlerVO)
        dataMap.put("imports", createImport(table.getColumnList()))
        def filePath = handlerVO.getOutputPath() + "/entity/" + table.getClassName() + handlerVO.getEntitySuffix() + ".java"
        GeneratorUtil.writeFile(filePath, template, dataMap)
    }

    /**
     * 查询实体类创建方法
     *
     * @param table - 数据库表对象
     * @param packagePath - 包路径
     * @param config - 模板配置对象
     * @param handlerVO - 代码生成器界面设置内容
     * @throws IOException - IO 异常
     * @throws TemplateException - 模板异常
     */
    private void createParam(Table table, String packagePath, Configuration config,
                             HandlerVO handlerVO) throws IOException, TemplateException {
        /* 获取或创建一个模板 */
        def template = config.getTemplate("Param.ftl", "UTF-8")
        def dataMap = getDataMap(table, packagePath, handlerVO)
        dataMap.put("imports", createParamImport(table.getColumnList()))
        dataMap.put("columns", getParamColumns(table.getColumnList()))
        def filePath = handlerVO.getOutputPath() + "/param/" + table.getClassName() + "Param.java"
        GeneratorUtil.writeFile(filePath, template, dataMap)
    }

    private def createImport(List<Column> columnList) {
        def imports = []
        def numMap = [:]
        columnList.each { column ->
            if (StringUtils.isNotBlank(column.getFullType()) && null == numMap[column.getFullType()]) {
                imports << column.getFullType()
                numMap.put(column.getFullType(), 1)
            }
        }
        return imports
    }

    private def createParamImport(List<Column> columnList) {
        def imports = []
        def numMap = [:]
        columnList.each { column ->
            if (StringUtils.isNotBlank(column.getFullType()) && null == numMap[column.getFullType()]
                    && StringUtils.contains(GeneratorConstants.PARAM_TYPE, column.getFullType())) {
                imports << column.getFullType()
                numMap.put(column.getFullType(), 1)
            }
        }
        return imports
    }
    
    private def getParamColumns(List<Column> columnList) {
        def paramColumns = []
        columnList.each { column ->
            if (StringUtils.contains(GeneratorConstants.PARAM_TYPE, column.getFullType())) {
                def paramColumnBegin = new Column()
                paramColumnBegin.setColumnName(column.getColumnName() + GeneratorConstants.TIME_PREFIX)
                paramColumnBegin.setColumnSize(column.getColumnSize())
                paramColumnBegin.setIsNullable(column.getIsNullable())
                paramColumnBegin.setIsPrimary(column.getIsPrimary())
                paramColumnBegin.setRemark(column.getRemark() + "开始时间")
                paramColumnBegin.setTypeName(column.getTypeName())
                paramColumns << paramColumnBegin
                
                def paramColumnEnd = new Column()
                paramColumnEnd.setColumnName(column.getColumnName() + GeneratorConstants.TIME_SUFFIX)
                paramColumnEnd.setColumnSize(column.getColumnSize())
                paramColumnEnd.setIsNullable(column.getIsNullable())
                paramColumnEnd.setIsPrimary(column.getIsPrimary())
                paramColumnEnd.setRemark(column.getRemark() + "结束时间")
                paramColumnEnd.setTypeName(column.getTypeName())
                paramColumns << paramColumnEnd
            }
        }
        return paramColumns
    }

}
